import {
	defineStore
} from 'pinia';

export const useFootmarkStore = defineStore('footmark', {
	state: () => {
		return {
			footlist: [
				// 	{
				// 	"day": "2023-03-03",
				// 	"list": [
				// 		{
				//			id:1
				// 			"pic": "",
				// 			"title": "",
				// 			"price": "",
				// 		},		
				// 		{
				//			id:1
				// 			"pic": "",
				// 			"title": "",
				// 			"price": "",
				// 		},		
				// 	]
				// },
			]
		};
	},
	actions: {
		//初始化历史
		initFoot() {
			//登录 init 未登录 清除
			if (true) {
				uni.getStorage({
					key: 'storage_foot',
					success: (res) => {
						this.footlist = res.data;
						if (this.footlist.length > 7) {
							this.footlist.pop();
						}
					}
				});
			} else {
				this.footlist = []
			}
		},
		//新增历史
		addFoot(payload) {
			//判断今天
			let now = new Date(Date.now());
			let y = now.getFullYear();
			let m = now.getMonth() + 1;
			m = m < 10 ? "0" + m : m;
			let d = now.getDate();
			d = d < 10 ? "0" + d : d;
			let today = `${y}-${m}-${d}`;
			let _id = payload.id;
			//判断是否有记录 没有则新增一条记录
			let _ind = this.footlist.findIndex(item => {
				return item.day == today;
			})
			//存在
			if (_ind >= 0) {
				//存在  判断是否含有该商品记录
				let todayVal = this.footlist[_ind];
				let _sind = todayVal.list.findIndex(item => {
					return item.id == _id;
				});
				if (_sind >= 0) {
					//存在则更新顺序
					this.footlist[_ind].list.splice(_sind, 1);
				};
				this.footlist[_ind].list.unshift(payload);
			} else {
				//不存在则新增
				let obj = {};
				obj.day = today;
				obj.list = [];
				obj.list.unshift(payload);
				this.footlist.unshift(obj);
			}
			uni.setStorage({
				key: 'storage_foot',
				data: this.footlist
			});
		},
		//删除历史
		delFoot(payload) {
			const {
				id,
				day
			} = payload;
			let _ind = this.footlist.findIndex(item => {
				return item.day == day;
			})
			this.footlist[_ind].list.forEach((item, index) => {
				if (item.id == id) {
					this.footlist[_ind].list.splice(index, 1);
				}
			})
			if (this.footlist[_ind].list.length == 0) {
				this.footlist.splice(_ind, 1);
			}
			uni.setStorage({
				key: 'storage_foot',
				data: this.footlist
			});
		},
	},
	getters: {
		footLength: (state) => {
			if (state.footlist.length == 0) return 0;
			let _length = 0;
			for (let i = 0; i < state.footlist.length; i++) {
				for (let j = 0; j < state.footlist[i].list.length; j++) {
					_length += 1
				}
			}
			return _length;
		}
	}
});